import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Tag, Modal, Descriptions, message, Space, Empty } from 'antd';
import { FilePdfOutlined, CheckOutlined, CloseOutlined, EyeOutlined } from '@ant-design/icons';
import { getMyOffers, acceptOffer, rejectOffer } from '../../../api/recruitment';

/**
 * 候选人录取信息页面
 * 显示候选人收到的录取通知
 */
const CandidateOffers = () => {
    const [loading, setLoading] = useState(false);
    const [offers, setOffers] = useState([]);
    const [currentOffer, setCurrentOffer] = useState(null);
    const [detailVisible, setDetailVisible] = useState(false);

    useEffect(() => {
        fetchOffers();
    }, []);

    // 获取录取信息
    const fetchOffers = async () => {
        setLoading(true);
        try {
            const response = await getMyOffers();
            setOffers(response.data || []);
        } catch (error) {
            console.error('获取录取信息失败:', error);
            message.error('获取录取信息失败');
        } finally {
            setLoading(false);
        }
    };

    // 查看录取详情
    const handleViewDetail = (record) => {
        setCurrentOffer(record);
        setDetailVisible(true);
    };

    // 接受录取
    const handleAccept = (record) => {
        Modal.confirm({
            title: '确认接受录取',
            content: `您确定要接受"${record.position_title}"的录取通知吗？`,
            okText: '确认接受',
            cancelText: '取消',
            onOk: async () => {
                try {
                    await acceptOffer(record.id);
                    message.success('已接受录取通知');
                    fetchOffers();
                } catch (error) {
                    console.error('接受录取失败:', error);
                    message.error('接受录取失败');
                }
            }
        });
    };

    // 拒绝录取
    const handleReject = (record) => {
        Modal.confirm({
            title: '确认拒绝录取',
            content: `您确定要拒绝"${record.position_title}"的录取通知吗？此操作不可撤销。`,
            okText: '确认拒绝',
            okType: 'danger',
            cancelText: '取消',
            onOk: async () => {
                try {
                    await rejectOffer(record.id);
                    message.success('已拒绝录取通知');
                    fetchOffers();
                } catch (error) {
                    console.error('拒绝录取失败:', error);
                    message.error('拒绝录取失败');
                }
            }
        });
    };

    // 下载录取函
    const handleDownload = (record) => {
        message.info('下载录取函功能开发中...');
    };

    const columns = [
        {
            title: '职位名称',
            dataIndex: 'position_title',
            key: 'position_title',
        },
        {
            title: '部门',
            dataIndex: 'department_name',
            key: 'department_name',
        },
        {
            title: '录取日期',
            dataIndex: 'offer_date',
            key: 'offer_date',
        },
        {
            title: '入职日期',
            dataIndex: 'start_date',
            key: 'start_date',
        },
        {
            title: '薪资待遇',
            dataIndex: 'salary',
            key: 'salary',
            render: (text) => `¥${parseFloat(text).toLocaleString()}/月`,
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status) => {
                const statusMap = {
                    'pending': { color: 'orange', text: '待处理' },
                    'accepted': { color: 'green', text: '已接受' },
                    'rejected': { color: 'red', text: '已拒绝' },
                    'expired': { color: 'gray', text: '已过期' },
                };
                
                const { color, text } = statusMap[status] || { color: 'default', text: status };
                return <Tag color={color}>{text}</Tag>;
            },
        },
        {
            title: '有效期至',
            dataIndex: 'expiry_date',
            key: 'expiry_date',
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <Button 
                        type="link" 
                        icon={<EyeOutlined />}
                        onClick={() => handleViewDetail(record)}
                    >
                        详情
                    </Button>
                    {record.status === 'pending' && (
                        <>
                            <Button 
                                type="primary" 
                                icon={<CheckOutlined />}
                                onClick={() => handleAccept(record)}
                            >
                                接受
                            </Button>
                            <Button 
                                danger
                                icon={<CloseOutlined />}
                                onClick={() => handleReject(record)}
                            >
                                拒绝
                            </Button>
                        </>
                    )}
                    {(record.status === 'accepted' || record.status === 'pending') && (
                        <Button 
                            type="primary" 
                            icon={<FilePdfOutlined />}
                            onClick={() => handleDownload(record)}
                        >
                            下载录取函
                        </Button>
                    )}
                </Space>
            ),
        },
    ];

    return (
        <>
            <Card title="我的录取通知">
                {offers.length > 0 ? (
                    <Table
                        columns={columns}
                        dataSource={offers}
                        rowKey="id"
                        loading={loading}
                    />
                ) : (
                    <Empty description="暂无录取通知" />
                )}
            </Card>

            {/* 录取详情弹窗 */}
            <Modal
                title="录取详情"
                open={detailVisible}
                onCancel={() => setDetailVisible(false)}
                footer={[
                    <Button key="close" onClick={() => setDetailVisible(false)}>
                        关闭
                    </Button>,
                    currentOffer?.status === 'pending' && (
                        <>
                            <Button 
                                key="accept" 
                                type="primary" 
                                onClick={() => {
                                    setDetailVisible(false);
                                    handleAccept(currentOffer);
                                }}
                            >
                                接受录取
                            </Button>
                            <Button 
                                key="reject" 
                                danger
                                onClick={() => {
                                    setDetailVisible(false);
                                    handleReject(currentOffer);
                                }}
                            >
                                拒绝录取
                            </Button>
                        </>
                    ),
                    (currentOffer?.status === 'accepted' || currentOffer?.status === 'pending') && (
                        <Button 
                            key="download" 
                            type="primary" 
                            icon={<FilePdfOutlined />}
                            onClick={() => handleDownload(currentOffer)}
                        >
                            下载录取函
                        </Button>
                    ),
                ].filter(Boolean)}
                width={700}
            >
                {currentOffer && (
                    <Descriptions bordered column={2}>
                        <Descriptions.Item label="职位名称" span={2}>{currentOffer.position_title}</Descriptions.Item>
                        <Descriptions.Item label="部门">{currentOffer.department_name}</Descriptions.Item>
                        <Descriptions.Item label="工作地点">{currentOffer.location}</Descriptions.Item>
                        <Descriptions.Item label="录取日期">{currentOffer.offer_date}</Descriptions.Item>
                        <Descriptions.Item label="入职日期">{currentOffer.start_date}</Descriptions.Item>
                        <Descriptions.Item label="薪资待遇">{`¥${parseFloat(currentOffer.salary).toLocaleString()}/月`}</Descriptions.Item>
                        <Descriptions.Item label="有效期至">{currentOffer.expiry_date}</Descriptions.Item>
                        <Descriptions.Item label="状态" span={2}>
                            {(() => {
                                const statusMap = {
                                    'pending': { color: 'orange', text: '待处理' },
                                    'accepted': { color: 'green', text: '已接受' },
                                    'rejected': { color: 'red', text: '已拒绝' },
                                    'expired': { color: 'gray', text: '已过期' },
                                };
                                
                                const { color, text } = statusMap[currentOffer.status] || { color: 'default', text: currentOffer.status };
                                return <Tag color={color}>{text}</Tag>;
                            })()}
                        </Descriptions.Item>
                        <Descriptions.Item label="工作职责" span={2}>{currentOffer.job_description}</Descriptions.Item>
                        <Descriptions.Item label="福利待遇" span={2}>{currentOffer.benefits}</Descriptions.Item>
                        <Descriptions.Item label="附加说明" span={2}>{currentOffer.notes}</Descriptions.Item>
                    </Descriptions>
                )}
            </Modal>
        </>
    );
};

export default CandidateOffers; 